<template>
  <el-card class="login-card" shadow="hover">
    <h2 class="title">Login</h2>

    <el-form :model="form" status-icon>
      <el-form-item label="Username" :rules="[{ required: true, message: 'Please input username', trigger: 'blur' }]">
        <el-input v-model="form.username" placeholder="Enter username"></el-input>
      </el-form-item>

      <el-form-item label="Password" :rules="[{ required: true, message: 'Please input password', trigger: 'blur' }]">
        <el-input v-model="form.password" type="password" placeholder="Enter password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleLogin" :loading="loading" style="width: 100%">Login</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '@/stores/auth';
import {useRouter} from "vue-router";
import instance from "@/utils/http";

const form = ref({
  username: '',
  password: '',
  type:"admin"
});

const loading = ref(false);
const authStore = useAuthStore();
const router = useRouter()

const handleLogin = async () => {
  loading.value = true;
  try {
    const response = await instance.post('/auth/login', form.value,{
      headers:{
        type:"admin"
      }
    }); // 替换为真实的登录API
    const { data, code, message } = response.data;
    if(code !== 200){
      ElMessage.error(message)
      return
    }
    // 存储 token 到 Pinia 和 localStorage
    authStore.setToken(data.username);
    authStore.setUid(data.id);
    localStorage.setItem('token', data.username); // 如果需要长期保存 token，存储到 localStorage
    // 显示成功信息
    ElMessage.success('Login successful');
    // 跳转到用户主页
    router.push('/'); // 跳转到首页
  } catch (error) {
    ElMessage.error('Login failed, please check your credentials');
  } finally {
    loading.value = false;
  }
};


</script>

<style scoped>
.login-card {
  width: 400px;
  margin: 100px auto;
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 20px;
}
</style>
